package com.im.security.handler;

import com.alibaba.fastjson.JSON;
import com.im.security.annotation.LoginUser;
import com.im.security.dto.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 */
//@Component
@Slf4j
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        System.out.println("LoginUserHandlerMethodArgumentResolver.supportsParameter");
        // 参数类型是UserEntity并且形参上加了@LoginUser注解，才能调用resolveArgument方法
        boolean assignableFrom = parameter.getParameterType().isAssignableFrom(LoginVo.class);
        boolean annotation = parameter.hasParameterAnnotation(LoginUser.class);
        System.out.println("parameterType："+parameter.getParameterType());
        System.out.println("assignableFrom："+assignableFrom);
        System.out.println("annotation："+annotation);
        return assignableFrom && annotation;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        System.out.println("LoginUserHandlerMethodArgumentResolver.resolveArgument");

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String userInfo = requestAttributes.getRequest().getHeader("userInfo");
        log.debug("userInfo:{}",userInfo);
        LoginVo userToken = JSON.parseObject(userInfo, LoginVo.class);
        log.debug("userToken:{}",userToken);
        return userToken;
    }
}